package com.jessechanrui.template.pdfbox;

import com.jessechanrui.template.FileUtil;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.PDPageContentStream;
import org.apache.pdfbox.pdmodel.common.PDRectangle;
import org.apache.pdfbox.pdmodel.font.PDType0Font;
import org.apache.pdfbox.pdmodel.graphics.color.PDColor;
import org.apache.pdfbox.pdmodel.graphics.color.PDDeviceRGB;
import org.apache.pdfbox.pdmodel.graphics.state.PDExtendedGraphicsState;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class PdfBasicSettings {

    // 纸张大小和边距设置
    private static final PDRectangle PAGE_SIZE = PDRectangle.A4; // 纸张大小：A4
    private static final float MARGIN_LEFT = 50;                // 左边距
    private static final float MARGIN_RIGHT = 50;               // 右边距
    private static final float MARGIN_TOP = 70;                 // 上边距（预留页眉空间）
    private static final float MARGIN_BOTTOM = 70;              // 下边距（预留页脚空间）

    // 计算实际内容区域
//    private static final float CONTENT_WIDTH = PAGE_SIZE.getWidth() - MARGIN_LEFT - MARGIN_RIGHT;
//    private static final float CONTENT_HEIGHT = PAGE_SIZE.getHeight() - MARGIN_TOP - MARGIN_BOTTOM;

    public static void main(String[] args) {
        try (PDDocument document = new PDDocument()) {
            // 添加3个页面作为示例
            for (int i = 0; i < 3; i++) {
                PDPage page = new PDPage(PAGE_SIZE);
                document.addPage(page);

                // 创建内容流，用于添加内容到页面
                try (PDPageContentStream contentStream = new PDPageContentStream(document, page)) {
                    // 设置透明度（可选）
                    PDExtendedGraphicsState r0 = new PDExtendedGraphicsState();
                    r0.setNonStrokingAlphaConstant(0.5f);
                    contentStream.setGraphicsStateParameters(r0);

                    // 加载字体（支持中文）
                    PDType0Font fontRegular = PDType0Font.load(document, new File(FileUtil.getBaseDir(),"fonts/simhei.ttf")); // 黑体
                    PDType0Font fontBold = PDType0Font.load(document, new File(FileUtil.getBaseDir(),"fonts/simhei.ttf"));   // 这里用同样的黑体作为粗体示例

                    // 绘制页眉
                    drawHeader(contentStream, fontBold, document.getNumberOfPages());

                    // 绘制页脚
                    drawFooter(contentStream, fontRegular, document.getNumberOfPages());

                    // 绘制正文内容
                    drawContent(contentStream, fontRegular, i + 1);
                }
            }

            // 保存PDF文档
            document.save(new File(FileUtil.getOutDir(), "pdf_with_settings.pdf"));
            System.out.println("PDF创建成功！");

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 绘制页眉
     */
    private static void drawHeader(PDPageContentStream contentStream, PDType0Font font, int pageNumber) throws IOException {
        // 设置页眉颜色（深蓝色）
        PDColor headerColor = new PDColor(new float[]{0.0f, 0.0f, 0.5f}, PDDeviceRGB.INSTANCE);
        contentStream.setNonStrokingColor(headerColor);

        // 设置字体和字号
        contentStream.setFont(font, 12);

        // 页眉文本
        String headerText = "PDFBox 示例文档";
        float headerX = (PAGE_SIZE.getWidth() - font.getStringWidth(headerText) / 1000 * 12) / 2; // 居中
        float headerY = PAGE_SIZE.getHeight() - MARGIN_TOP / 2;

        // 绘制页眉文本
        contentStream.beginText();
        contentStream.newLineAtOffset(headerX, headerY);
        contentStream.showText(headerText);
        contentStream.endText();

        // 绘制页眉下划线
        contentStream.setStrokingColor(headerColor);
        contentStream.moveTo(MARGIN_LEFT, headerY - 5);
        contentStream.lineTo(PAGE_SIZE.getWidth() - MARGIN_RIGHT, headerY - 5);
        contentStream.stroke();
    }

    /**
     * 绘制页脚
     */
    private static void drawFooter(PDPageContentStream contentStream, PDType0Font font, int pageNumber) throws IOException {
        // 设置页脚颜色（灰色）
        PDColor footerColor = new PDColor(new float[]{0.5f, 0.5f, 0.5f}, PDDeviceRGB.INSTANCE);
        contentStream.setNonStrokingColor(footerColor);

        // 设置字体和字号
        contentStream.setFont(font, 10);

        // 页脚左侧：日期
        String dateText = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
        contentStream.beginText();
        contentStream.newLineAtOffset(MARGIN_LEFT, MARGIN_BOTTOM / 2);
        contentStream.showText(dateText);
        contentStream.endText();

        // 页脚右侧：页码
        String pageText = "第 " + pageNumber + " 页";
        float pageTextWidth = font.getStringWidth(pageText) / 1000 * 10;
        contentStream.beginText();
        contentStream.newLineAtOffset(PAGE_SIZE.getWidth() - MARGIN_RIGHT - pageTextWidth, MARGIN_BOTTOM / 2);
        contentStream.showText(pageText);
        contentStream.endText();

        // 绘制页脚上划线
        contentStream.setStrokingColor(footerColor);
        contentStream.moveTo(MARGIN_LEFT, MARGIN_BOTTOM);
        contentStream.lineTo(PAGE_SIZE.getWidth() - MARGIN_RIGHT, MARGIN_BOTTOM);
        contentStream.stroke();
    }

    /**
     * 绘制正文内容
     */
    private static void drawContent(PDPageContentStream contentStream, PDType0Font font, int pageNumber) throws IOException {
        // 恢复默认颜色（黑色）
        PDColor textColor = new PDColor(new float[]{0.0f, 0.0f, 0.0f}, PDDeviceRGB.INSTANCE);
        contentStream.setNonStrokingColor(textColor);

        // 设置正文字体和字号
        contentStream.setFont(font, 12);

        // 正文内容
        String title = "第 " + pageNumber + " 页 内容";
        String content = "这是一个使用 PDFBox 设置字体、颜色、纸张大小、边距、页眉和页脚的示例。\n\n" +
                "PDFBox 是一个开源的 Java 库，用于处理 PDF 文档的创建、解析、提取内容、修改和验证。\n" +
                "通过本示例，你可以了解如何设置 PDF 的各种基础参数。";

        // 绘制标题（红色）
        PDColor titleColor = new PDColor(new float[]{1.0f, 0.0f, 0.0f}, PDDeviceRGB.INSTANCE);
        contentStream.setNonStrokingColor(titleColor);
        contentStream.beginText();
        contentStream.newLineAtOffset(MARGIN_LEFT, PAGE_SIZE.getHeight() - MARGIN_TOP);
        contentStream.showText(title);
        contentStream.endText();

        // 绘制正文（黑色）
        contentStream.setNonStrokingColor(textColor);
        contentStream.beginText();
        contentStream.newLineAtOffset(MARGIN_LEFT, PAGE_SIZE.getHeight() - MARGIN_TOP - 30);
        contentStream.setLeading(18); // 设置行间距

        // 处理换行
        String[] lines = content.split("\n");
        for (String line : lines) {
            contentStream.showText(line);
            contentStream.newLine();
        }
        contentStream.endText();
    }
}

